input(), print(), str(), int(), float(), len(), random.randint(), random.random(), ...
def hello(): # def: a keyword to define a function
print("Hello!")
hello() # Invocation of the function hello(), or calling the function hello()
hello()
hello()
def hello():
print("Hello!")
??? hello(name): # name is called a parameter; A value is passed into name when hello() is called.
print("Hello " + name + "!")
hello('John') # 'John' is called an argument here. We may say the argument 'John' is passed to hello().
name = 'Ruth'
hello(name) # The value stored in name is passed to hello().
hello() and saved in the variable name inside hello().input(). Here is an example. Any errors? How to fix?
??? isEven(num): # A value is passed into num when isEven() is invoked.
if num % 2 == 0:
return True # The value True is returned, passed back, to the code that calls this function isEven().
else???
??? False
print(isEven(888)) # isEvent(888) is executed, and the result from isEvent(888) is passed to print().
number = input("Enter an integer: ")
result = isEven(number)
print(result)
name and count are changed after the function hello() is called?
name = 'John';
count = 1;
??? hello(name):
count = 2;
name = name * count
print("Hello " + name + "!")
hello(name)
print(name + ", " + count)
name and count, are used in the function hello() and outside of all functions.
The variables defined in a function can be used only inside the function.
The space where those variables defined in a function is called a local scope.
The space outside of all functions is called the global scope.
Here are several rules regarding local variables, global variables, and their scopes.
count in hello() global or local?
Is the variable name in hello() global or local?
Let's try the next example.
name = 'John';
count = 2;
??? hello():
count = 1; # count: global variable or local variable?
print("Hello " + name + "!") # name: global variable or local variable?
hello()
print(name + ", " + str(count))
name = 'John';
count = 0;
def hello(name):
global count # count: global variable
count = count + 1; # count: global variable or local variable?
print("Hello " + name + str(count) + "!")
hello('Ruth')
hello(name)
print(count) # what will be printed?
printStars(num) that prints num-many stars.
We may need to use print(..., end=''), where end='' makes print() print in the same line.
printChars(char, num) that prints num-many chars.
printTriangle(num) that prints a tree of stars.
This function can use printStars() or printChars().
E.g., when num is 5,
* ** *** **** *****
printTriangle() may be used.
*
**
***
****
*****
-+-+-.+-+-+-+.'M', and all the other characters are ' '.
The position of 'M' should be randomly decided.
The function returns the string.
'|'.
E.g., |M|1|0|0|1|M|2|M|1|0| for board = "M1001M2M10".